<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElTag,ElSwitch,ElForm,ElFormItem,ElInput,ElUpload,FormRules,FormInstance,UploadInstance,ElLink } from 'element-plus'
import { Table } from '@/components/Table'
import { SelVerion,lzrAddVersion} from '@/api/houtaiguanli'
import { useTable } from '@/hooks/web/useTable'
import { TableData,TableDatatwo } from '@/api/table/types'
import { h, ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { TableColumn } from '@/types/table'
import { FormSchema } from '@/types/form'
import { ElMessage } from 'element-plus'

const ruleFormRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()

const { register, tableObject, methods } = useTable<TableData>({
  getListApi: SelVerion,
  response: {
    list: 'list',
    total: 'total'
  },
  defaultParams: {
    title: 's'
  }
})

const { getList, setSearchParams } = methods
getList()

const { t } = useI18n()

//表格的虚拟数据
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '序号',
    type: 'index',
  },
  {
    field: 'version_code',
    label:'版本编号'
  },
  {
    field: 'file_name',
    label:'版本名称',
  },
  {
    field: 'app_name',
    label:'App名称',
  },
  {
    field: 'true_name',
    label:'创建人',
  },
  {
    field: 'create_date',
    label:'执行时间',
    formatter: (row, column, cellValue, index) => {
      let format = 'YYYY-mm-dd HH:MM:SS'
      let date = new Date(cellValue);
      const dataItem = {
        'Y+': date.getFullYear().toString(),
        'm+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
        'H+': date.getHours().toString(),
        'M+': date.getMinutes().toString(),
        'S+': date.getSeconds().toString(),
      };
      Object.keys(dataItem).forEach((item) => {
        const ret = new RegExp(`(${item})`).exec(format);
        if (ret) {
          format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
        }
      });
      return format
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const delLoading = ref(false)

const actionType = ref('')

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

allSchemas.searchSchema = reactive<FormSchema[]>([
  {
    field: 'versionCode',
    label: '版本编号',
    component: 'Input',
  },
  {
    field: 'createDate',
    component: 'DatePicker',
    label: '创建时间',
    componentProps: {
      type: 'date',
      valueFormat:'YYYY-MM-DD'
    }
  },
  {
    field: 'createUser',
    label: '创建人',
    component: 'Input',
  },
])
let WenjianData = reactive({
  versionName:'',
  versionCode:'',
  appName:'',
  fileName:'',
  filePath:'',
  createDate:'',
  createId: ''
})

const rules = reactive<FormRules>({
  appName: [
    { required: true, message: '请输入App名称！', trigger: 'blur' }
  ],
  versionName: [
    { required: true, message: '请输入版本名称！', trigger: 'blur' },
  ],
  fileName: [
    {
      required: true,
      message: '请输入软件名称！',
      trigger: 'blur',
    },
  ],
  versionCode: [
    {
      required: true,
      message: '请输入版本号！',
      trigger: 'blur',
    },
  ]
})

let bianliang = ref(false)
let purview = ref(false)
const AddBanben = () => {
  bianliang.value = false
  WenjianData = reactive({
    versionName:'',
    versionCode:'',
    appName:'',
    fileName:'',
    filePath:'',
    createDate:'',
    createId: ''
  })
  purview.value = true
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (bianliang.value == true){
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        uploadRef.value!.submit()
      }
    })
  } else {
    ElMessage.error('请上传软件！')
  }
}
const beforeUpload = (file) => {
  var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
  const extension = testmsg === "rar";
  if (!extension ) {
    ElMessage({
      message: "上传文件只能是.rar格式!",
      type: "warning",
    })
  }
  return extension;
}
const handleExceed = (files, fileList) =>{
  ElMessage.error(`最多上传1个版本！`);
}

const handleFileChange = (file, fileList) =>{
  //判断图片列表长度大于0时，代表已上传软件
  if(fileList.length > 0){
    bianliang.value = true
  }
}
const handleSuccess =async (response) =>{
  if(response>0){
    ElMessage({
      message: "添加版本成功！",
      type: "success",
    })
    purview.value = false
    getList();
  }else {
    ElMessage.error('添加版本失败')
  }
}
</script>

<template>
  <div class="pre_home">
    <div class="div_tit" style="margin-bottom: 20px">
      <div class="div_ic"></div>
      <p class="tit_span">
        版本管理列表
      </p>
    </div>
    <div class="div_index">
      <div class="div_index_title">
        <Icon icon="tabler:search" />
        筛选查询
        <div style="float: right;margin-right: 30px">
          <ElButton @click="AddBanben" type="primary" round>添加版本</ElButton>
        </div>
      </div>
    </div>
  <ContentWrap>
    <div style="width: 2000px">
      <Search
              :model="{ title: '' }"
              :schema="allSchemas.searchSchema"
              @search="setSearchParams"
              @reset="setSearchParams"
      />
    </div>
  </ContentWrap>
  <ContentWrap>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList.slice((tableObject.currentPage - 1) * tableObject.pageSize,tableObject.currentPage * tableObject.pageSize)"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElLink type="success" :href="row.file_path">下载</ElLink>
      </template>
    </Table>
  </ContentWrap>
  </div>
  <Dialog v-model="purview" open-delay="500" title="上传压缩包">
    <ElForm :model="WenjianData" label-width="120px" :rules="rules" ref="ruleFormRef">
      <ElFormItem label="App名称:" prop="appName">
        <ElInput placeholder="请输入App名称" v-model="WenjianData.appName" />
      </ElFormItem>
      <ElFormItem label="版本名称:" prop="versionName">
        <ElInput placeholder="请输入版本名称" v-model="WenjianData.versionName" />
      </ElFormItem>
      <ElFormItem label="软件名称:" prop="fileName">
        <ElInput placeholder="请输入软件名称" v-model="WenjianData.fileName" />
      </ElFormItem>
      <ElFormItem label="版本号:" prop="versionCode">
        <ElInput placeholder="请输入版本号" v-model="WenjianData.versionCode" />
      </ElFormItem>
      <div style="vertical-align: center">
        <ElFormItem ref="crFile">
          <ElUpload
                  ref="uploadRef"
                  class="upload-demo"
                  accept=".rar"
                  :auto-upload="false"
                  action="http://localhost:8081/personnel/lzrAddVersion"
                  :limit="1"
                  :before-upload="beforeUpload"
                  :on-exceed="handleExceed"
                  :on-success="handleSuccess"
                  :on-change="handleFileChange"
                  :data="{
                                    'appName':WenjianData.appName,
                                    'fileName':WenjianData.fileName,
                                    'versionName':WenjianData.versionName,
                                    'versionCode':WenjianData.versionCode
                            }"
          >
            <ElButton size="small" type="primary">点击上传版本</ElButton>
          </ElUpload>
        </ElFormItem>
      </div>
      <div style="text-align: center">
        <ElButton type="primary" @click="submitForm(ruleFormRef)">
          保存
        </ElButton>
        <ElButton @click="purview = false">{{ t('dialogDemo.close') }}</ElButton>
      </div>
    </ElForm>
  </Dialog>
</template>

<style lang="less" scoped>
  .pre_home{
    width:100%;
    height:100%;
  }
  .div_tit{
    margin-left: 0.1%;
    width:99%;
    height:50px;
    background-color:#F2F2F2;
    border:2px solid #E6E6E6;
    position: relative;
  }
  .tit_span{
    margin-left:10px;
    margin-top:-20px;
    color:#999999;
  }

  .div_ic{
    width:5px;
    height:20px;
    background-color:#1ABC9C;
    margin-top:15px;
  }
  .div_btn{
    margin-left: 2.5%;
    margin-right:20px;
    width:96%;
    height:50px;
    margin-bottom:10px;
  }
  .btn_li_item{
    margin-top:13px;
    width:140px;
    float:left;
  }
  .div_btn_class{
    width:130px;
    height:35px;
    background-color: #31A99F;
    color: white;
    border: 1px solid black;
  }
  .div_btn_classtwo{
    width:130px;
    height:35px;
    background-color: white;
    color: black;
    border: 1px solid black;
  }
  .span_Num{
    color: #ff4624;
    font-weight: bold;
  }
  .div_index_ul1{
    overflow: hidden;
    width: 210px;
    position: absolute;
    right: -17px;
  }
  .div_index_title{
    width:100%;
    height:55px;
    background-color:#F3F3F3;
    border-bottom:1px solid #E6E6E6;
    font-weight:bold;
    line-height:55px;
    font-size:16px;
    text-indent:18px;
    color:#666666;
  }
</style>
